package com.basker.pisces.service.exception;

import org.springframework.util.Assert;

import com.basker.pisces.service.dto.DefaultServiceResult;
import com.basker.pisces.service.dto.IServiceResult;
import com.basker.pisces.service.dto.ServiceResultFactory;

/**
 * 将其他系统api返回的错误对象封装成一个异常
 *
 * @author hangwen
 */
public class ServiceResultWrapperException extends RuntimeException {

    private static final long serialVersionUID = 333589040574586539L;

    private String targetService;
    private IServiceResult<?> result;

    public ServiceResultWrapperException(String targetService, IServiceResult<?> result) {
        Assert.hasText(targetService, "parameter 'targetService' is required");
        Assert.notNull(result, "parameter 'result' is required");

        this.targetService = targetService;
        this.result = result;
    }

    @Override
    public String getMessage() {
        return "target service '" + targetService + "':" + this.result.getMessage();
    }

    public IServiceResult<?> getResult() {
        return result;
    }

    public String getTargetService() {
        return targetService;
    }

    /**
     * 将封装的{@link IServiceResult}转成一个新的实例，其消息会包含目标服务的信息
     *
     * @return
     */
    public IServiceResult<?> toResult() {
        DefaultServiceResult<Object> another = ServiceResultFactory.build(this.result);
        another.setMessage(this.getMessage());

        return another;
    }
}